<?php
final class Core {
	
	/**
	 *
	 * @var Logger
	 */
	private $_logger;
	/**
	 *
	 * @var Core
	 */
	private static $_instance = null;
	/**
	 * 私有构造函数，该类不能实例化
	 */
	private function __construct() {
		Logger::configure ( ROOT_PATH . 'config/log_config.xml' );
		$this->_logger = Logger::getLogger ( __CLASS__ );
	}
	
	/**
	 * 获取单个实例
	 *
	 * @return Core
	 */
	public static function getSingleton() {
		if (self::$_instance == null) {
			return new Core ();
		}
		return self::$_instance;
	}
	
	/**
	 * dispatch
	 * 核心方法<br />
	 * 负责框架内对请求的路由
	 */
	public function dispatch() {
		$uriParser = URIParser::getSingleton ();
		$this->_doAction ( $uriParser->getController (), $uriParser->getAction () );
	}
	
	/**
	 *
	 * @param string $controller        	
	 * @param string $action        	
	 * @throws Exception
	 */
	private function _doAction($controller, $action) {
		$className = ucfirst ( $controller );
		$methodName = strtolower ( $action ) . 'Action';
		try {
			if (! class_exists ( $className )) {
				throw new Exception ( 'Can not find controller' );
			}
			$instance = new $className ();
			if (! method_exists ( $instance, $methodName )) {
				throw new Exception ( 'Can not find action' );
			}
			$instance->$methodName ();
		} catch ( Exception $e ) {
			$this->_logger->error ( 'Request a non-exists resource. ' . $e->getMessage () . '. in CLASS [' .__CLASS__.'] at LINE '. __LINE__);
			$this->_throw404 ();
		}
	}
	
	/**
	 * <h2>send a 404</h2>
	 */
	private function _throw404() {
		header ( "HTTP/1.0 404 Not Found" );
		exit ();
	}
}
